import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
  callDifyWorkflowStream,
  generateUserId,
  checkDifyApiHealth,
  type DifyWorkflowRequest,
  type DifyStreamResponse,
} from '@/api/difyWorkflow'

export interface ChatMessage {
  id: string
  type: 'user' | 'assistant' | 'system'
  content: string
  timestamp: Date
  status?: 'sending' | 'success' | 'error'
}

export const useDifyWorkflowStore = defineStore('difyWorkflow', () => {
  // 状态
  const messages = ref<ChatMessage[]>([])
  const isConnecting = ref(false)
  const isStreaming = ref(false)
  const currentUserId = ref<string>(generateUserId())
  const error = ref<string | null>(null)
  const apiHealth = ref<boolean | null>(null)

  // 当前流式响应的消息ID
  const currentStreamMessageId = ref<string | null>(null)

  // 处理内容，移除think标签并处理Markdown
  function processContent(rawContent: string): string {
    let processedContent = rawContent
    
    // 检查是否包含完整的<think></think>标签
    const thinkRegex = /<think>[\s\S]*?<\/think>/g
    const hasCompleteThink = thinkRegex.test(processedContent)
    
    if (hasCompleteThink) {
      // 移除所有完整的<think></think>标签及其内容
      processedContent = processedContent.replace(thinkRegex, '')
      // 清理多余的空行
      processedContent = processedContent.replace(/\n\s*\n\s*\n/g, '\n\n')
      processedContent = processedContent.trim()
    }
    
    return processedContent
  }

  // 方法
  function addMessage(message: Omit<ChatMessage, 'id' | 'timestamp'>): string {
    const id = 'msg_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
    const newMessage: ChatMessage = {
      id,
      timestamp: new Date(),
      ...message,
    }
    messages.value.push(newMessage)
    return id
  }

  function updateMessage(messageId: string, updates: Partial<ChatMessage>) {
    const messageIndex = messages.value.findIndex((m) => m.id === messageId)
    if (messageIndex >= 0) {
      messages.value[messageIndex] = { ...messages.value[messageIndex], ...updates }
    }
  }

  async function sendMessage(input: string): Promise<void> {
    if (isStreaming.value) {
      throw new Error('已有流式请求正在进行中')
    }

    error.value = null

    // 添加用户消息
    const userMessageId = addMessage({
      type: 'user',
      content: input,
      status: 'success',
    })

    // 添加助手消息占位符
    const assistantMessageId = addMessage({
      type: 'assistant',
      content: '',
      status: 'sending',
    })

    currentStreamMessageId.value = assistantMessageId
    isStreaming.value = true

    const request: DifyWorkflowRequest = {
      query:  input ,
      response_mode: 'streaming',
      user: currentUserId.value
    }

    try {
      await callDifyWorkflowStream(
        request,
        // onMessage
        (data: DifyStreamResponse) => {
          console.log('接收到流式数据:', data)

          if (currentStreamMessageId.value) {
            const currentMessage = messages.value.find((m) => m.id === currentStreamMessageId.value)
            if (currentMessage) {
              // 根据不同的事件类型处理数据
              let contentToAdd = ''

              if (data.event === 'message' && data.answer) {
                // 处理消息事件，提取answer字段
                contentToAdd = data.answer
              } else if (data.event === 'text_chunk' && data.data?.text) {
                // 处理文本块事件
                contentToAdd = data.data.text
              } else if (data.event === 'workflow_started') {
                // 工作流开始事件，可以显示状态信息
                contentToAdd = '\n⚙️ 工作流已启动...\n\n'
              } else if (data.event === 'node_started' && data.data?.title) {
                // 节点开始事件，显示节点信息
                contentToAdd = `📦 正在执行: ${data.data.title}\n`
              }

              // 如果有内容需要添加，更新消息
              if (contentToAdd) {
                const newContent = currentMessage.content + contentToAdd
                const processedContent = processContent(newContent)
                
                updateMessage(currentStreamMessageId.value, {
                  content: processedContent,
                  status: 'sending',
                })
              }
            }
          }
        },
        // onError
        (streamError: Error) => {
          error.value = `流式请求错误: ${streamError.message}`
          if (currentStreamMessageId.value) {
            updateMessage(currentStreamMessageId.value, {
              status: 'error',
            })
          }
          isStreaming.value = false
          currentStreamMessageId.value = null
        },
        // onComplete
        () => {
          if (currentStreamMessageId.value) {
            updateMessage(currentStreamMessageId.value, {
              status: 'success',
            })
          }
          isStreaming.value = false
          currentStreamMessageId.value = null
          console.log('流式响应完成')
        },
      )
    } catch (err) {
      error.value = err instanceof Error ? err.message : '发送消息失败'
      if (currentStreamMessageId.value) {
        updateMessage(currentStreamMessageId.value, {
          status: 'error',
        })
      }
      isStreaming.value = false
      currentStreamMessageId.value = null
    }
  }

  async function checkApiHealth(): Promise<void> {
    isConnecting.value = true
    try {
      apiHealth.value = await checkDifyApiHealth()
    } catch (err) {
      apiHealth.value = false
      error.value = '检查API连通性失败'
    } finally {
      isConnecting.value = false
    }
  }

  function clearMessages() {
    messages.value = []
    error.value = null
  }

  function regenerateUserId() {
    currentUserId.value = generateUserId()
  }

  return {
    // 状态
    messages,
    isConnecting,
    isStreaming,
    currentUserId,
    error,
    apiHealth,

    // 方法
    addMessage,
    updateMessage,
    sendMessage,
    checkApiHealth,
    clearMessages,
    regenerateUserId,
  }
})
